package com.qys.training.openapi.sender;

import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.ITopic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

/**
 * @author Winstone
 * @date 2020/8/5 - 8:01 下午
 */
public class AliveSender implements Runnable {

    private static final Logger logger = LoggerFactory.getLogger(AliveSender.class);
    private HazelcastInstance client;
    private String clientId;

    public AliveSender(HazelcastInstance client,String uuid) {
        this.client = client;
        this.clientId = uuid;
    }

    public void run() {
        sendAliveMessage();
    }

    public void sendAliveMessage() {

        // 查找 存活列表中是否 包含该实例
        String aliveCache = (String) client.getMap("aliveMap").get(clientId);
        ITopic<String> topic = client.getTopic("alive");

        // 如果没有缓存
        if (aliveCache == null || aliveCache.equals("")) {
            logger.info("【{}】-- 存活状态 已发送 --->{}", clientId, new Date());
        }
        // 发送Topic
        topic.publish(clientId);

        // 间隔3秒发送
        try {
            Thread.sleep(3000);
            sendAliveMessage();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
